package com.plat.api.common.task;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.servlet.multipart.UploadFile;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.plat.api.common.OrderType;
import com.plat.api.dao.api.PlatWechatLiveRoomDao;
import com.plat.api.entity.api.PlatWechatLiveRoomEntity;
import com.plat.api.redis.RedisCache;
import com.plat.api.util.M3u8SolveUtil;
import com.plat.api.util.QiNiuUtil;
import com.plat.api.util.YmalPropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/10/12
 * Time: 18:28
 * Description: 下载回放视频
 */
@Slf4j
public class DownloadReplay implements Runnable {
    private static String DownloadReplayKEY = "DownloadReplayKEY";
    private PlatWechatLiveRoomDao platWechatLiveRoomDao;
    private WxMaService wxMaService;
    private RedisCache redisCache;
    private String url = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=";

    public DownloadReplay(PlatWechatLiveRoomDao platWechatLiveRoomDao, WxMaService wxMaService, RedisCache redisCache) {
        this.platWechatLiveRoomDao = platWechatLiveRoomDao;
        this.wxMaService = wxMaService;
        this.redisCache = redisCache;
        ;
    }

    @Override
    public void run() {
        log.info("启动下载回放");
        while (true) {
            try {
                Thread.sleep(1000 * 10);
                long time = 24 * 60 * 1000*60;//240分钟
                long time_1 = 15 * 60 * 1000;//240分钟
                Date beforeDate = new Date(new Date().getTime() - time);//30分钟前的时间
                Date nowPLusTen = new Date(new Date().getTime() - time_1);//10分钟前的时间 现在十分之前
                String value1 = DateUtil.format(beforeDate, "yyyy-MM-dd HH:mm:ss");//30分钟前的时间);
                String value2 = DateUtil.format(nowPLusTen, "yyyy-MM-dd HH:mm:ss");
                PlatWechatLiveRoomEntity roomEntity = platWechatLiveRoomDao.createLambdaQuery()
                        .andEq("live_status", 103)
                        .andEq("replay_create_status", 0).andBetween("live_end_time", value1, value2).single();
                if (roomEntity != null) {
                    log.info("回放可以下载");
                    roomEntity.setReplayCreateStatus(1);
                    platWechatLiveRoomDao.updateById(roomEntity);
                    String accessToken = wxMaService.getAccessToken();
                    Map<String, Object> param = new HashMap<>();
                    param.put("action", "get_replay");
                    param.put("room_id", roomEntity.getRoomId());
                    param.put("start", "0");
                    param.put("limit", 100);
                    String result = HttpUtil.post(url + accessToken, JSONObject.toJSONString(param));
                    log.info("[回看下载更新信息：{}]", result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    JSONArray jsonArray = jsonObject.getJSONArray("live_replay");
                    roomEntity.setReplayCreateStatus(2);
                    if (jsonArray.size() > 0) {
                        JSONObject res = (JSONObject) jsonArray.get(0);
                        roomEntity.setMediaUrl(res.getString("media_url"));
//                        roomEntity.setLiveStatus(OrderType.REPLAY);
                        String url = M3u8SolveUtil.download(res.getString("media_url"));
                        roomEntity.setMediaUrl(url);
                        log.info("[更行的信息：{}]", JSONObject.toJSONString(roomEntity));
                        log.info("[更新信息：{}]", JSONObject.toJSONString(roomEntity));
                    }
                    platWechatLiveRoomDao.updateById(roomEntity);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("[下载视频发生错误，错误信息={}]", e.getMessage());
            }
        }

    }

}
